include("../../static/js/config.js");
include("../../static/js/common.js");

$(function () {

    var form;
    layui.use(['laydate', 'form'], function () {
        var laydate = layui.laydate;
        //日期
        laydate.render({
            type: 'datetime',
            elem: '#createDate',
            format: 'yyyy-MM-dd HH:mm:ss'
        });

        var message = '';
        form = layui.form;
        form.verify({
            username: function (value) {
                var orginUsername = $("#orginUsername").val();
                if (orginUsername === value){
                    return;
                }
                asyncRequest("/admin/admin/checkUsername", {username:value}, function (res) {
                    if (res.code === 200){
                        if (res.data === false){
                            message = '用户名已存在，请重新输入！';
                        }
                    }
                });
                if (message !== ''){
                    return message;
                }
            }
        });

        form.on('submit(update)', function(data){
            var id = $("#id").val();
            var username = $("#username").val();
            var password = $("#password").val();

            request("/admin/admin/update", {id:id, username:username, password:password}, function (data) {
                if (data.code == 200){
                    layer.msg("操作成功", {icon: 1});
                    setTimeout(function () {
                        if (window.parent){
                            window.parent.layer.closeAll();
                            window.parent.location.reload();
                        }
                    }, 3000);
                } else {
                    layer.msg(data.msg, {icon: 5});
                }
            });
            return false;
        });

        init();
    });

    function init() {
       request('/admin/admin/detail', {id: getParam('id')}, function(res){
           if (res.code == 200){
               $('#id').val(res.data.id);
               $('#username').val(res.data.username);
               $('#orginUsername').val(res.data.username);
               $('#createDate').val(res.data.createDate);
           } else {
               layer.msg(res.msg, {icon: 5});
           }
       });
    }
});